package com.example.shiweilong.myserver;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button mStartService;
    private Button mStopService;
    private Button mBindService;
    private Button mUnbindService;

    private MyService.DownloadBinder mDownloadBinder;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mDownloadBinder = (MyService.DownloadBinder) service;
            mDownloadBinder.startDowndload();
            mDownloadBinder.getProgress();
        }
        @Override public void onServiceDisconnected(ComponentName name) {}
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mStartService = findViewById(R.id.start_service);
        mStopService = findViewById(R.id.stop_service);
        mBindService = findViewById(R.id.bind_service);
        mUnbindService = findViewById(R.id.unbind_service);

        mStartService.setOnClickListener(this);
        mStopService.setOnClickListener(this);
        mBindService.setOnClickListener(this);
        mUnbindService.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch(view.getId()){

            case R.id.start_service:
                Intent startIntent = new Intent(this,MyService.class);
                startService(startIntent);
                break;

            case R.id.stop_service:
                Intent stopIntent = new Intent(this,MyService.class);
                startService(stopIntent);
                break;

            case R.id.bind_service:
                Intent bindIntent = new Intent(this,MyService.class);
                bindService(bindIntent,connection,BIND_AUTO_CREATE);
                break;

            case R.id.unbind_service:
                unbindService(connection);
                break;

            default:
                break;
        }

    }
}
